<script lang="ts" setup>
import type { RequestConfig } from "@/pkg/requests";
import { event } from "@/pkg/requests";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/user";
import { useNotification } from "@/pkg/ZNotification.vue";
import { useLoadingBar } from "@/pkg/ZLoadingBar.vue";

const router = useRouter(),
  route = useRoute(),
  userStore = useUserStore(),
  notification = useNotification(),
  loadingBar = useLoadingBar();
// 统一 Http Status Code Error 处理
event.on("onError", ({ status, message }) => {
  loadingBar?.error();
  if (status === 401) {
    userStore.logout();
    return (
      route.name &&
      (route.name as string).startsWith("todos") &&
      router.push({ name: "login" })
    );
  }
  notification?.error(message);
});
// 统一响应消息处理
event.on("onResponse", (response) => {
  // 全局处理加载条
  loadingBar?.end();
  const { data, config } = response;
  if (data.message && !(config as RequestConfig).ignoreNotifyError)
    data.success
      ? notification?.success(data.message)
      : notification?.error(data.message);
});
event.on("onRequest", () => {
  loadingBar?.start();
});
defineOptions({
  render() {
    return false;
  },
});
</script>
